package com.cy.pj.sys.service.impl;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysLogDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysLog;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysLogService;

@Service
public class SysLogServiceImpl implements SysLogService {

	@Autowired
	private SysLogDao sysLogDao;
	
	//@Async 描述的方法为一个异步切入点方法(此方法会运行在spring框架提供的一个线程中)
	@Async//@Async描述的方法表示要运行在一个独立线程中(这个线程由spring框架内置的线程池来提供)
	@Transactional(propagation = Propagation.REQUIRES_NEW)//让saveObject方法始终运行在一个自己独立的事务中
	@Override
	public void saveObject(SysLog entity) {
		System.out.println("SysLogServiceImpl.saveObject.thread->"+Thread.currentThread().getName());
		//模拟耗时操作(假设写日志时耗时的)
		try{Thread.sleep(5000);}catch(Exception e) {}
		sysLogDao.insertObject(entity);
	}
	
	@RequiresPermissions("sys:log:delete")
	@Override
	public int deleteObjects(Integer... ids) {
		//1.参数校验
		if(ids==null||ids.length==0)
			throw new IllegalArgumentException("请先选择");
		//2.执行删除
		int rows=sysLogDao.deleteObjects(ids);
		//3.返回结果
		if(rows==0)
			throw new ServiceException("记录可能已经不存在");
		return rows;
	}
	
	@Override
	public PageObject<SysLog> findPageObjects(Long pageCurrent, String username) {
		//1.参数校验
		if(pageCurrent==null||pageCurrent<1)
			throw new IllegalArgumentException("页码值不正确");//IllegalArgumentException 无效参数异常
		//2.基于条件查询总记录数并校验
		long rowCount=sysLogDao.getRowCount(username);
		if(rowCount==0)
			throw new ServiceException("没有找到对应记录");//自定义异常要具备更好业务含义
		//3.查询当前页要呈现的用户日志行为信息
		int pageSize=5;
		long startIndex=(pageCurrent-1)*pageSize;
		List<SysLog> records=sysLogDao.findPageObjects(username, startIndex, pageSize);
		//4.封装两次查询结果并返回
		//4.1基于set方法为属性赋值
//		PageObject<SysLog> pageObject=new PageObject<>();
//		pageObject.setRowCount(rowCount);
//		pageObject.setRecords(records);
//		pageObject.setPageCurrent(pageCurrent);
//		pageObject.setPageSize(pageSize);
//		long pageCount=rowCount/pageSize;
//		if(rowCount%pageSize!=0) {
//			pageCount++;
//		}
//		pageObject.setPageCount(pageCount);
//		return pageObject;
		//4.3基于构造方法为属性赋值
		return new PageObject<>(rowCount, records, pageSize, pageCurrent);
	}

}






